package cn.bdqn.demo.seckill;

import cn.bdqn.demo.bean.Order;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class SecKillService {
    private static final int TIMEOUT = 10 * 1000; //超时时间 10s
    private static final int TRY_TIME = 5; //重试次数
    @Resource
    RedisLock redisLock;
    @Resource
    StockCacheService stockCacheService;

    @Resource
    OrderJmsSenderService orderJmsSenderService;

    public int secKill(String productId, Integer userId) {
        return secKill(productId, userId, true);
    }
    /**
     *
     * @param productId
     * @param userId
     * @return 1 - success, others failed
     */
    public int secKill(String productId, Integer userId, boolean locked) {
        long time = System.currentTimeMillis() + TIMEOUT ;
        if(locked) {
            boolean gotlock = false;
            for (int i = 0; i < TRY_TIME; i++) {
                gotlock = redisLock.lock(productId, String.valueOf(time));
                if(!gotlock) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    break;
                }
            }
            if(!gotlock) {
                System.out.println(Thread.currentThread().getName() + "并发量太多，没抢到");
                return -1;
            }
        }

        /*****如果被锁，则下面的代码都不会被执行*******/
        try {
            //1.查询该商品库存，为0则活动结束。
            int stockNum = stockCacheService.get(productId);
            if (stockNum == 0) {
                //注意：库存为0时候也需要解锁所有放在finally块
//                throw new SellException(100,"活动结束");
//                System.out.println("活动结束");
                return 0;
            } else {
                //2.下单(模拟不同用户openid不同)
                Order order = new Order();
                order.setCost(999);
                order.setOrderDate(new Date());
                order.setProductId(productId);
                order.setUserId(userId);
                orderJmsSenderService.send(order);
                //3.减库存
                stockNum = stockNum - 1;
                stockCacheService.set(productId, stockNum);
                System.out.println(Thread.currentThread().getName()+"抢购成功");
            }
        }catch (Throwable e) {
            e.printStackTrace();
            return -3;
        } finally {
            if(locked) {
                redisLock.unlock(productId, String.valueOf(time));
            }
        }
        return 1;
    }

    public int getStock(String productId) {
        return stockCacheService.get(productId);
    }
}
